//
//  YWWorkReminderViewController.m
//  maintain
//
//  Created by Kyo on 16/6/21.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWWorkReminderViewController.h"
#import "UIColor+CustomColors.h"
#import "MJRefresh.h"
#import "UIScrollView+EmptyDataSet.h"
#import "YWMacro.h"
#import "YWConst.h"

#import "YWWorkReminderManager.h"
#import "YWCirculationDetailViewController.h"

#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWInspectionMissionModel.h"
#import "YWKeepWatchMission.h"
#import "YWCommonTool.h"
#import "YWKeepWatchViewController.h"
#import "YWInspectionDetailViewController.h"
#import "YWInspectionLocationViewController.h"
#import "YWMissionDetailsViewController.h"
//#import "YWMaterialStockOut.h"
//#import "YWMaterialReturn.h"
//#import "YWMaterialApply.h"
//#import "YWMaterialRecordTableViewController.h"
#import "YWReplyManager.h"
#import "YWNoReadReplyTableViewController.h"
#import "YWEwinManager.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "YWOffLineMissionCell.h"
#import "YWDailyReportCell.h"
#import "YWMissionExpirationCell.h"
#import "YWMissionCancelCell.h"
#import "YWMissionModifyCell.h"
#import "YWSystemNoticeCell.h"
#import "YWAppVersionCell.h"

#import "YWKeepWatchMissionManager.h"
#import "YWInspectionMissionManager.h"
#import "YWMeterReadingManager.h"
#import "YWAttendanceManager.h"
#import "YWUploadFailedItem.h"

#import "YWUploadFailedRecordTableViewController.h"
#import "YWWebViewController.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWTroubleMissionModel.h"
#import "YWTroubleMissionManager.h"
#import "YWReportTroubleManager.h"

@interface YWWorkReminderViewController ()<UITableViewDataSource,UITableViewDelegate,YWDailyReportCellDelegate,DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSIndexPath *clickIndexPath;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) NSMutableArray *uploadFailMissionArray;
@property (nonatomic, copy) NSMutableAttributedString *contentString;
//@property (nonatomic, strong) NSMutableArray *unReadReplyArray;
//@property (nonatomic, strong) UIButton *unReadButton;
//@property (nonatomic, strong) UIView *headView;
//@property (nonatomic, strong) UIView *nullHeadView;
//@property (nonatomic, assign) BOOL restTableHeadView;
@end

@implementation YWWorkReminderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if (_reminderType == YWReminderType_uploadFailed) {
        self.title = NSLocalizedString(@"reminderTypeOfUploadFailed", nil);//@"离线任务提醒";
    }else if (_reminderType == YWReminderType_missionExpiration){
        self.title = NSLocalizedString(@"reminderTypeOfMissionExpiration", nil);//@"任务过期提醒";
    }else if (_reminderType == YWReminderType_missionChange){
        self.title = NSLocalizedString(@"reminderTypeOfMissionChange", nil);//@"任务变更提醒";
    }else if (_reminderType == YWReminderType_missionCancel){
        self.title = NSLocalizedString(@"reminderTypeOfMissionCancel", nil);//@"任务取消提醒";
    }else if (_reminderType == YWReminderType_keepWatchNoBody){
        self.title = NSLocalizedString(@"reminderTypeOfKeepWatchNoBody", nil);//@"无人巡更提醒";
    }else if (_reminderType == YWReminderType_inspectionNoBody){
        self.title = NSLocalizedString(@"reminderTypeOfInspectionNoBody", nil);//@"无人巡查提醒";
    }else if (_reminderType == YWReminderType_dailyRport){
        self.title = NSLocalizedString(@"reminderTypeOfDailyRport", nil);//@"工作日报";
    }else if (_reminderType == YWReminderType_systemNotice){
        self.title = NSLocalizedString(@"reminderTypeOfSystemNotice", nil);//@"系统提醒";
    }else if (_reminderType == YWReminderType_appVersionNotice){
        self.title = NSLocalizedString(@"reminderTypeOfAppVersionNotice", nil);//@"易维保新版本提醒";
    }else if (_reminderType == YWReminderType_replyMessage){
        self.title = NSLocalizedString(@"reminderTypeOfReplyMessage", nil);//@"评论提醒";
    }else{
        self.title = NSLocalizedString(@"remind", nil);//@"提醒";
    }
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _page = 1;
    
    if (_reminderType == YWReminderType_uploadFailed) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshRemindOfUploadFailedCount) name:KPushBackgroundUploadRecordSuccessNotification object:nil];
        //上传失败的记录
        [self setupUploadFailedRecordsArray];
    }
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    
    if (_reminderType >=YWReminderType_missionExpiration && _reminderType <= YWReminderType_appVersionNotice) {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
        self.tableView.mj_footer.automaticallyHidden = YES;
        // 马上进入刷新状态
        [self.tableView.mj_header beginRefreshing];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView:) name:KPostRefreshCirculationDetailVCNoti object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView:) name:KPostCirculationHandlerNotification object:nil];
}

- (void)refreshTop{
    _page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    YWWeakSelf(weakSelf);
    dispatch_group_t group = dispatch_group_create();
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (refreshType == YWTableViewFreshTypeUp) {
            _page++;
        }
        dispatch_group_enter(group);
        [[YWWorkReminderManager shareManager] requestReminderWithType:_reminderType page:_page pageSize:10 complete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            weakSelf.dataSource = nil;
            weakSelf.uploadFailMissionArray = nil;
            [weakSelf setupUploadFailedRecordsArray];
            [weakSelf.tableView reloadData];
            //上次阅读时间
            NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970]*1000;
            [[YWEwinManager shareManager] saveLastReadTime:currentTime type:YWUnReadCountTypeRemind];
        });
    });
}

-(UITableView *)tableView{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
        [tableView registerClass:[YWOffLineMissionCell class] forCellReuseIdentifier:YWOffLineMissionCellIdentifier];
        [tableView registerClass:[YWDailyReportCell class] forCellReuseIdentifier:YWDailyReportCellIdentifier];
        [tableView registerClass:[YWMissionExpirationCell class] forCellReuseIdentifier:YWMissionExpirationCellIdentifier];
        [tableView registerClass:[YWMissionCancelCell class] forCellReuseIdentifier:YWMissionCancelCellIdentifier];
        [tableView registerClass:[YWMissionModifyCell class] forCellReuseIdentifier:YWMissionModifyCellIdentifier];
        [tableView registerClass:[YWSystemNoticeCell class] forCellReuseIdentifier:YWSystemNoticeCellIdentifier];
        [tableView registerClass:[YWAppVersionCell class] forCellReuseIdentifier:YWAppVersionCellIdentifier];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.sectionFooterHeight = 1.0;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.estimatedRowHeight = 44.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        
        [self.view addSubview:tableView];
        _tableView = tableView;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
    }
    return _tableView;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
        //NSArray *reminderArray = [[YWWorkReminderManager shareManager] reminderWithPage:self.page];
        
        if (_reminderType == YWReminderType_uploadFailed && _uploadFailMissionArray.count) {
            [_dataSource addObject:_contentString];
        }else{
            NSArray *reminderArray = [[YWWorkReminderManager shareManager] reminderWithType:_reminderType page:_page];
            [_dataSource addObjectsFromArray:reminderArray];
        }
    }
    return _dataSource;
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    id object = self.dataSource[indexPath.row];
    if ([object isKindOfClass:[NSMutableAttributedString class]]) {
        YWOffLineMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWOffLineMissionCellIdentifier];
        cell.totalCount = _uploadFailMissionArray.count;
        cell.recordString = _contentString;
        return cell;
    }else if ([object isKindOfClass:[YWReminder class]]){
        YWReminder *reminder = (YWReminder*)object;
        if (reminder.type == YWReminderType_missionExpiration || reminder.type == YWReminderType_keepWatchNoBody || reminder.type == YWReminderType_inspectionNoBody) {
            //任务过期，无人巡查，无人巡更
            YWMissionExpirationCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMissionExpirationCellIdentifier];
            cell.reminder = reminder;
            return cell;
        }else if (reminder.type == YWReminderType_dailyRport){
            //工作日报
            YWDailyReportCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDailyReportCellIdentifier];
            cell.delegate = self;
            cell.reminder = reminder;
            return cell;
        }else if (reminder.type == YWReminderType_missionCancel){
            //任务取消
            YWMissionCancelCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMissionCancelCellIdentifier];
            cell.reminder = reminder;
            return cell;
        }else if (reminder.type == YWReminderType_missionChange){
            //任务变更
            YWMissionModifyCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMissionModifyCellIdentifier];
            cell.reminder = reminder;
            return cell;
        }else if (reminder.type == YWReminderType_systemNotice){
            //系统通知
            YWSystemNoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWSystemNoticeCellIdentifier];
            cell.reminder = reminder;
            return cell;
        }else if (reminder.type == YWReminderType_appVersionNotice){
            //app新版本提醒
            YWAppVersionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWAppVersionCellIdentifier];
            cell.reminder = reminder;
            return cell;
        }
    }
    return [[UITableViewCell alloc] init];
}

#pragma mark - UITableViewDataDelegate mothods
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    id object = self.dataSource[indexPath.row];
//    if ([object isKindOfClass:[NSMutableAttributedString class]]) {
//        return  [tableView fd_heightForCellWithIdentifier:YWOffLineMissionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWOffLineMissionCell *cell) {
//            cell.totalCount = _uploadFailMissionArray.count;
//            cell.recordString = _contentString;
//        }];
//    }else if ([object isKindOfClass:[YWReminder class]]){
//        YWReminder *reminder = (YWReminder*)object;
//        if (reminder.type == YWReminderType_missionExpiration || reminder.type == YWReminderType_keepWatchNoBody || reminder.type == YWReminderType_inspectionNoBody) {
//            //任务过期，无人巡查，无人巡更
//            return  [tableView fd_heightForCellWithIdentifier:YWMissionExpirationCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMissionExpirationCell *cell) {
//                cell.reminder = reminder;
//            }];
//        }else if (reminder.type == YWReminderType_dailyRport){
//            //工作日报
//            return  [tableView fd_heightForCellWithIdentifier:YWDailyReportCellIdentifier cacheByIndexPath:indexPath configuration:^(YWDailyReportCell *cell) {
//                cell.reminder = reminder;
//            }];
//        }else if (reminder.type == YWReminderType_missionCancel){
//            //任务取消
//            return  [tableView fd_heightForCellWithIdentifier:YWMissionCancelCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMissionCancelCell *cell) {
//                cell.reminder = reminder;
//            }];
//        }else if (reminder.type == YWReminderType_missionChange){
//            //任务变更
//            return  [tableView fd_heightForCellWithIdentifier:YWMissionModifyCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMissionModifyCell *cell) {
//                cell.reminder = reminder;
//            }];
//        }else if (reminder.type == YWReminderType_systemNotice){
//            //系统通知
//            return  [tableView fd_heightForCellWithIdentifier:YWSystemNoticeCellIdentifier cacheByIndexPath:indexPath configuration:^(YWSystemNoticeCell *cell) {
//                cell.reminder = reminder;
//            }];
//        }else if (reminder.type == YWReminderType_appVersionNotice){
//            //app新版本提醒
//            return  [tableView fd_heightForCellWithIdentifier:YWAppVersionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWAppVersionCell *cell) {
//                cell.reminder = reminder;
//            }];
//        }
//    }
//    return 0;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    id object = self.dataSource[indexPath.row];
    if ([object isKindOfClass:[NSMutableAttributedString class]]) {
        YWUploadFailedRecordTableViewController *uploadFailedRecordVC = [[YWUploadFailedRecordTableViewController alloc] init];
        uploadFailedRecordVC.dataSource = self.uploadFailMissionArray;
        [self.navigationController pushViewController:uploadFailedRecordVC animated:YES];
    }else if ([object isKindOfClass:[YWReminder class]]){
        YWReminder *reminder = (YWReminder*)object;
        if (reminder.type != YWReminderType_dailyRport && reminder.type != YWReminderType_systemNotice && reminder.type!= YWReminderType_missionCancel) {
            if (reminder.missionType == YWMaintenanceTypeTrouble) {
                //维修
                YWTroubleMissionModel * troubleMissionModel = [[YWTroubleMissionManager shareManager] troubleMissionModelWithTroubleId:reminder.relationId];
                if (troubleMissionModel) {
                    [self pushViewControllerWithMission:troubleMissionModel];
                }else{
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionNotFound", nil)];
                }
            }else if (reminder.missionType == YWMaintenanceTypeDetection || reminder.missionType == YWMaintenanceTypeUpkeep){
                //检测保养
                YWMaintenanceMission *maintenanceMission = [YWDetectAndUpkeepManager maintenanceMissionWithMissionId:reminder.relationId];
                if (maintenanceMission) {
                    [self pushViewControllerWithMission:maintenanceMission];
                }else{
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionNotFound", nil)];
                }
            }else if (reminder.type == YWReminderType_appVersionNotice){
                if (reminder.linkUrl.length) {
                    YWWebViewController* webVC = [[YWWebViewController alloc] init];
                    webVC.title = NSLocalizedString(@"reminderTypeOfAppVersionNotice", nil);
                    webVC.passURL = reminder.linkUrl;
                    [self.navigationController pushViewController:webVC animated:YES];
                }
            }else if (reminder.missionType == YWMaintenanceTypePatrol){
                //巡查
                YWInspectionMissionModel *inspectionMission = [[YWInspectionMissionManager shareManager] inspectionMissionWithMissionId:reminder.relationId];
                if (inspectionMission && inspectionMission.status == 0) {
                    [self pushViewControllerWithMission:inspectionMission];
                }else{
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionNotFoundOrExpiration", nil)];
                }
            }else{
                //巡更
                YWKeepWatchMission *keepWatchMission = [[YWKeepWatchMissionManager shareManager] keepWatchMissionWithMissionId:reminder.relationId];
                if (keepWatchMission && keepWatchMission.status == 0) {
                    [self pushViewControllerWithMission:keepWatchMission];
                }else{
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"missionNotFoundOrExpiration", nil)];
                }
            }
        }
    }
}

- (void)pushViewControllerWithMission:(id)missionObject{
    if ([missionObject isKindOfClass:[YWTroubleMissionModel class]]) {
        YWCirculationDetailViewController *circulationVC = [[YWCirculationDetailViewController alloc] init];
        circulationVC.troubleMissionModel = (YWTroubleMissionModel*)missionObject;
        [self.navigationController pushViewController:circulationVC animated:YES];
    }else if ([missionObject isKindOfClass:[YWMaintenanceMission class]]){
        YWMissionDetailsViewController* missionDetailsVC = [[YWMissionDetailsViewController alloc] init];
        missionDetailsVC.mission = (YWMaintenanceMission*)missionObject;
        [self.navigationController pushViewController:missionDetailsVC animated:YES];
    }else if ([missionObject isKindOfClass:[YWKeepWatchMission class]]){
        YWKeepWatchViewController *keepWatchVC = [[YWKeepWatchViewController alloc]init];
        keepWatchVC.notFromKeepWatchListVC = YES;
        keepWatchVC.keepWatchMission = (YWKeepWatchMission*)missionObject;
        [self.navigationController pushViewController:keepWatchVC animated:YES];
    }else if ([missionObject isKindOfClass:[YWInspectionMissionModel class]]){
        YWInspectionMissionModel *inspectionMission = (YWInspectionMissionModel*)missionObject;
        if (inspectionMission.inspectionLine.lineType == YWInspectionLineTypeLocation) {
            YWInspectionLocationViewController *inspectionLocationVC = [[YWInspectionLocationViewController alloc] init];
            inspectionLocationVC.inspectionMission = inspectionMission;
            inspectionLocationVC.notFromInspectionMissionVC = YES;
            [self.navigationController pushViewController:inspectionLocationVC animated:YES];
        }else{
            YWInspectionDetailViewController *detailVC = [[YWInspectionDetailViewController alloc] init];
            detailVC.inspectionMission = inspectionMission;
            detailVC.notFromInspectionMissionVC = YES;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

- (NSMutableArray *)uploadFailMissionArray{
    if (!_uploadFailMissionArray) {
        _uploadFailMissionArray = [NSMutableArray array];
    }
    return _uploadFailMissionArray;
}

- (void)setupUploadFailedRecordsArray{
    if (!_uploadFailMissionArray) {
        _uploadFailMissionArray = [NSMutableArray array];
    }
    _contentString = [[NSMutableAttributedString alloc] init];
    //报障
    NSInteger location = 6;
    NSInteger maxCount = 0;
    NSArray *failedPostTroubleArray = [[YWReportTroubleManager shareManager] uploadFailedReportTroubleArray];
    if (failedPostTroubleArray.count) {
        YWUploadFailedItem *item = [[YWUploadFailedItem alloc] init];
        item.itemName = NSLocalizedString(@"postTroubleRecord", nil);
        item.itemArray = failedPostTroubleArray;
        item.isOpen = YES;
        [_uploadFailMissionArray addObject:item];
        
        NSString *postTroubleSring = [NSString stringWithFormat:@"%@: 共%lu%@",NSLocalizedString(@"postTroubleRecord", nil),(unsigned long)failedPostTroubleArray.count,NSLocalizedString(@"tiao", nil)];
        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:postTroubleSring];
        NSRange attributeTextRange = NSMakeRange(location, postTroubleSring.length-location);
        [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:attributeTextRange];
        [_contentString appendAttributedString:attributedText];
        maxCount++;
    }
    
    //巡更
    NSArray *failedPatrolPointRecordArray = [[YWKeepWatchMissionManager shareManager] uploadFailedPatrolPointRecords];
    if (failedPatrolPointRecordArray.count) {
        YWUploadFailedItem *item = [[YWUploadFailedItem alloc] init];
        item.itemName = NSLocalizedString(@"keepWatchRecord", nil);
        item.itemArray = failedPatrolPointRecordArray;
        item.isOpen = YES;
        [_uploadFailMissionArray addObject:item];
        if (_contentString.length) {
            [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
        }
        NSString *keepwatchString = [NSString stringWithFormat:@"%@: 共%lu%@",NSLocalizedString(@"keepWatchRecord", nil),(unsigned long)failedPatrolPointRecordArray.count,NSLocalizedString(@"tiao", nil)];
        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:keepwatchString];
        NSRange attributeTextRange = NSMakeRange(location, keepwatchString.length-location);
        [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:attributeTextRange];
        [_contentString appendAttributedString:attributedText];
        maxCount++;
    }
    
    //巡查
    NSArray *failedInspectionRecordArray = [[YWInspectionMissionManager shareManager] uploadFailedInspectionRecords];
    if (failedInspectionRecordArray.count) {
        YWUploadFailedItem *item = [[YWUploadFailedItem alloc] init];
        item.itemName = NSLocalizedString(@"inspectionRecords", nil);//@"巡查记录";
        item.itemArray = failedInspectionRecordArray;
        item.isOpen = YES;
        [_uploadFailMissionArray addObject:item];
        
        if (maxCount==2) {
            [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n......"]];
        }else if (maxCount<2) {
            if (_contentString.length) {
                [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
            }
            NSString *inspectionString = [NSString stringWithFormat:@"%@: 共%lu%@",NSLocalizedString(@"inspectionRecords", nil),(unsigned long)failedInspectionRecordArray.count,NSLocalizedString(@"tiao", nil)];
            NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:inspectionString];
            NSRange attributeTextRange = NSMakeRange(location, inspectionString.length-location);
            [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:attributeTextRange];
            [_contentString appendAttributedString:attributedText];
        }
        maxCount++;
    }
    
    //检测
    NSArray *failedDetectionRecordArray = [[YWMissionManager shareManager] uploadFailedRecordsWithMaintenanceType:YWMaintenanceTypeDetection];
    if (failedDetectionRecordArray.count) {
        YWUploadFailedItem *item = [[YWUploadFailedItem alloc] init];
        item.itemName = NSLocalizedString(@"detectionRecord", nil);//@"检测记录";
        item.itemArray = failedDetectionRecordArray;
        item.isOpen = YES;
        [_uploadFailMissionArray addObject:item];
        
        if (maxCount==2) {
            [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n......"]];
        }else if (maxCount<2) {
            if (_contentString.length) {
                [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
            }
            NSString *detectionString = [NSString stringWithFormat:@"%@: 共%lu%@",NSLocalizedString(@"detectionRecord", nil),(unsigned long)failedDetectionRecordArray.count,NSLocalizedString(@"tiao", nil)];
            NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:detectionString];
            NSRange attributeTextRange = NSMakeRange(location, detectionString.length-location);
            [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:attributeTextRange];
            [_contentString appendAttributedString:attributedText];
        }
        maxCount++;
    }
    
    //保养
    NSArray *failedUpkeepRecordArray = [[YWMissionManager shareManager] uploadFailedRecordsWithMaintenanceType:YWMaintenanceTypeUpkeep];
    if (failedUpkeepRecordArray.count) {
        YWUploadFailedItem *item = [[YWUploadFailedItem alloc] init];
        item.itemName = NSLocalizedString(@"upkeepRecord", nil);//@"保养记录";
        item.itemArray = failedUpkeepRecordArray;
        item.isOpen = YES;
        [_uploadFailMissionArray addObject:item];
        
        if (maxCount==2) {
            [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n......"]];
        }else if (maxCount<2) {
            if (_contentString.length) {
                [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
            }
            NSString *upkeepString = [NSString stringWithFormat:@"%@: 共%lu%@",NSLocalizedString(@"upkeepRecord", nil),(unsigned long)failedUpkeepRecordArray.count,NSLocalizedString(@"tiao", nil)];
            NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:upkeepString];
            NSRange attributeTextRange = NSMakeRange(location, upkeepString.length-location);
            [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:attributeTextRange];
            [_contentString appendAttributedString:attributedText];
        }
        maxCount++;
    }
    
    //维修
    NSArray *failedTroubleRecordArray = [[YWMissionManager shareManager] uploadFailedRecordsWithMaintenanceType:YWMaintenanceTypeTrouble];
    if (failedTroubleRecordArray.count) {
        YWUploadFailedItem *item = [[YWUploadFailedItem alloc] init];
        item.itemName = NSLocalizedString(@"troubleRecord", nil);//@"维修记录";
        item.itemArray = failedTroubleRecordArray;
        item.isOpen = YES;
        [_uploadFailMissionArray addObject:item];
        
        if (maxCount==2) {
            [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n......"]];
        }else if (maxCount<2) {
            if (_contentString.length) {
                [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
            }
            NSString *troubleString = [NSString stringWithFormat:@"%@: 共%lu%@",NSLocalizedString(@"troubleRecord", nil),(unsigned long)failedTroubleRecordArray.count,NSLocalizedString(@"tiao", nil)];
            NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:troubleString];
            NSRange attributeTextRange = NSMakeRange(location, troubleString.length-location);
            [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:attributeTextRange];
            [_contentString appendAttributedString:attributedText];
        }
        maxCount++;
    }
    
    //抄表
    NSArray *failedMeterReadingArray = [[YWMeterReadingManager shareManager] meterReadingRecordWithUploadStatusFail];
    if (failedMeterReadingArray.count) {
        YWUploadFailedItem *item = [[YWUploadFailedItem alloc] init];
        item.itemName = NSLocalizedString(@"meterReadingRecord", nil);//@"抄表记录";
        item.itemArray = failedMeterReadingArray;
        item.isOpen = YES;
        [_uploadFailMissionArray addObject:item];
        
        if (maxCount==2) {
            [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n......"]];
        }else if (maxCount<2) {
            if (_contentString.length) {
                [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
            }
            NSString *meterReadingString = [NSString stringWithFormat:@"%@: 共%lu%@",NSLocalizedString(@"meterReadingRecord", nil),(unsigned long)failedMeterReadingArray.count,NSLocalizedString(@"tiao", nil)];
            NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:meterReadingString];
            NSRange attributeTextRange = NSMakeRange(location, meterReadingString.length-location);
            [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:attributeTextRange];
            [_contentString appendAttributedString:attributedText];
        }
        maxCount++;
    }
    
//    //签到
//    NSArray *failedAttendanceArray = [[YWAttendanceManager shareManager] attendanceRecordWithUploadStatusFail];
//    if (failedAttendanceArray.count) {
//        YWUploadFailedItem *item = [[YWUploadFailedItem alloc] init];
//        item.itemName = @"签到记录";
//        item.itemArray = failedAttendanceArray;
//        item.isOpen = YES;
//        [_uploadFailMissionArray addObject:item];
//        
//        if (maxCount==2) {
//            [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n......"]];
//        }else if (maxCount<2) {
//            if (_contentString.length) {
//                [_contentString appendAttributedString:[[NSAttributedString alloc]initWithString:@"\n"]];
//            }
//            NSString *attendanceString = [NSString stringWithFormat:@"签到记录: 共%lu条",(unsigned long)failedAttendanceArray.count];
//            NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithString:attendanceString];
//            NSRange attributeTextRange = NSMakeRange(location, attendanceString.length-location);
//            [attributedText setAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} range:attributeTextRange];
//            [_contentString appendAttributedString:attributedText];
//        }
//        maxCount++;
//    }
}

#pragma mark - YWDailyReportCellDelegate
- (void)handleShareButtonEvent:(UITableViewCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    id object = self.dataSource[indexPath.row];
    NSString *url = @"";
    if ([object isKindOfClass:[YWReminder class]]){
        YWReminder *reminder = (YWReminder*)object;
        url = reminder.linkUrl?:@"";
    }
    if (url.length<=0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"theSharedUrlIsNotExist", nil)];
        return;
    }
    NSURL *urlToShare = [NSURL URLWithString:url];
    NSString *textToShare = NSLocalizedString(@"share", nil);//@"分享";
    
    NSArray *activityItems = @[textToShare, urlToShare];
    UIActivityViewController *activityViewController = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    NSMutableArray *excludedActivityTypes =  [NSMutableArray arrayWithArray:@[UIActivityTypeAirDrop, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypeMail, UIActivityTypePostToTencentWeibo, UIActivityTypeSaveToCameraRoll, UIActivityTypeMessage, UIActivityTypePostToTwitter,UIActivityTypePostToFacebook]];
    activityViewController.excludedActivityTypes = excludedActivityTypes;
    
    [self presentViewController:activityViewController animated:YES completion:nil];
    activityViewController.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
        if ([activityType isEqualToString:UIActivityTypePostToWeibo]) {
            YWLog(@"新浪微博");
            if (completed) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"shareSucceed", nil)];
            }else{
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"shareFailed", nil)];
            }
        }else if ([activityType isEqualToString:@"com.tencent.xin.sharetimeline"]){
            YWLog(@"微信");
        }
    };
}

- (void)refreshTableView:(id)sender{
    _dataSource = nil;
    [self.tableView reloadData];
}

- (void)refreshRemindOfUploadFailedCount{
    _uploadFailMissionArray = nil;
    [self setupUploadFailedRecordsArray];
    _dataSource = nil;
    [self.tableView reloadData];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
